import React, { useState, useEffect } from 'react';
import { Layout, Menu, Tabs, Table, Button, Modal, Form, Input, Space, Select, Row, Col, message } from 'antd';
import { AppstoreOutlined, SearchOutlined } from '@ant-design/icons';

const { Header, Content } = Layout;
const { TabPane } = Tabs;

const App = () => {
  // 产品数据
  const [products, setProducts] = useState([
    { id: 1, name: '数据查询分析产品', description: '用于数据查询和分析的软件' },
    { id: 2, name: '客户关系管理系统', description: 'CRM系统' },
    { id: 3, name: '人力资源管理系统', description: 'HR系统' },
    { id: 4, name: '财务管理系统', description: '财务系统' },
    { id: 5, name: '项目管理软件', description: '用于项目规划和跟踪的软件' },
  ]);

  // 规格数据
  const [specifications, setSpecifications] = useState([
    { id: 1, productId: 1, name: '精简版', price: 99, period: '月' },
    { id: 2, productId: 1, name: '完整版', price: 199, period: '月' },
    { id: 3, productId: 1, name: '增强版', price: 299, period: '月' },
    { id: 4, productId: 2, name: '基础版', price: 149, period: '月' },
    { id: 5, productId: 2, name: '专业版', price: 249, period: '月' },
    { id: 6, productId: 3, name: '标准版', price: 179, period: '月' },
    { id: 7, productId: 4, name: '企业版', price: 399, period: '月' },
    { id: 8, productId: 5, name: '团队版', price: 129, period: '月' },
  ]);

  // 功能点数据
  const [features, setFeatures] = useState([
    { id: 1, productId: 1, specificationId: 1, name: '基础查询', usageLimit: 100 },
    { id: 2, productId: 1, specificationId: 2, name: '高级查询', usageLimit: 500 },
    { id: 3, productId: 1, specificationId: 3, name: 'AI分析', usageLimit: 1000 },
    { id: 4, productId: 2, specificationId: 4, name: '客户管理', usageLimit: 200 },
    { id: 5, productId: 2, specificationId: 5, name: '销售预测', usageLimit: 300 },
    { id: 6, productId: 3, specificationId: 6, name: '员工档案', usageLimit: 150 },
    { id: 7, productId: 4, specificationId: 7, name: '财务报表', usageLimit: 50 },
    { id: 8, productId: 5, specificationId: 8, name: '甘特图', usageLimit: 100 },
  ]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState('');
  const [form] = Form.useForm();

  const [filteredProducts, setFilteredProducts] = useState(products);
  const [filteredSpecifications, setFilteredSpecifications] = useState(specifications);
  const [filteredFeatures, setFilteredFeatures] = useState(features);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setFilteredProducts(products);
    setFilteredSpecifications(specifications);
    setFilteredFeatures(features);
  }, [products, specifications, features]);

  // 产品列
  const productColumns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '产品名称', dataIndex: 'name', key: 'name' },
    { title: '描述', dataIndex: 'description', key: 'description' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleEdit('product', record)}>编辑</a>
          <a onClick={() => handleDelete('product', record.id)}>删除</a>
        </Space>
      ),
    },
  ];

  // 规格列
  const specificationColumns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '产品ID', dataIndex: 'productId', key: 'productId' },
    { title: '规格名称', dataIndex: 'name', key: 'name' },
    { title: '价格', dataIndex: 'price', key: 'price' },
    { title: '周期', dataIndex: 'period', key: 'period' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleEdit('specification', record)}>编辑</a>
          <a onClick={() => handleDelete('specification', record.id)}>删除</a>
        </Space>
      ),
    },
  ];

  // 功能点列
  const featureColumns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '产品ID', dataIndex: 'productId', key: 'productId' },
    { title: '规格ID', dataIndex: 'specificationId', key: 'specificationId' },
    { title: '功能名称', dataIndex: 'name', key: 'name' },
    { title: '使用限制', dataIndex: 'usageLimit', key: 'usageLimit' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleEdit('feature', record)}>编辑</a>
          <a onClick={() => handleDelete('feature', record.id)}>删除</a>
        </Space>
      ),
    },
  ];

  const handleAdd = (type) => {
    form.resetFields();
    setModalType(type);
    setIsModalVisible(true);
  };

  const handleEdit = (type, record) => {
    form.setFieldsValue(record);
    setModalType(type);
    setIsModalVisible(true);
  };

  const handleDelete = (type, id) => {
    setLoading(true);
    Modal.confirm({
      title: '确认删除',
      content: '您确定要删除这条记录吗?',
      onOk() {
        return new Promise((resolve) => {
          setTimeout(() => {
            switch (type) {
              case 'product':
                setProducts(products.filter(item => item.id !== id));
                setSpecifications(specifications.filter(item => item.productId !== id));
                setFeatures(features.filter(item => item.productId !== id));
                break;
              case 'specification':
                setSpecifications(specifications.filter(item => item.id !== id));
                setFeatures(features.filter(item => item.specificationId !== id));
                break;
              case 'feature':
                setFeatures(features.filter(item => item.id !== id));
                break;
            }
            message.success('删除成功');
            setLoading(false);
            resolve();
          }, 1000);
        });
      },
      onCancel() {
        setLoading(false);
      },
    });
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      setLoading(true);
      setTimeout(() => {
        switch (modalType) {
          case 'product':
            const newProduct = {
              id: values.id || products.length + 1,
              name: values.name,
              description: values.description,
            };
            setProducts([...products, newProduct]);
            break;
          case 'specification':
            const newSpecification = {
              id: values.id || specifications.length + 1,
              productId: values.productId,
              name: values.name,
              price: values.price,
              period: values.period,
            };
            setSpecifications([...specifications, newSpecification]);
            break;
          case 'feature':
            const newFeature = {
              id: values.id || features.length + 1,
              productId: values.productId,
              specificationId: values.specificationId,
              name: values.name,
              usageLimit: values.usageLimit,
            };
            setFeatures([...features, newFeature]);
            break;
        }
        setIsModalVisible(false);
        setLoading(false);
        message.success(values.id ? '编辑成功' : '添加成功');
      }, 1000);
    });
  };
  const handleSearch = (type, value) => {
    switch (type) {
      case 'product':
        setFilteredProducts(products.filter(item =>
          item.name.toLowerCase().includes(value.toLowerCase()) ||
          item.description.toLowerCase().includes(value.toLowerCase())
        ));
        break;
      case 'specification':
        setFilteredSpecifications(specifications.filter(item =>
          item.name.toLowerCase().includes(value.toLowerCase())
        ));
        break;
      case 'feature':
        setFilteredFeatures(features.filter(item =>
          item.name.toLowerCase().includes(value.toLowerCase())
        ));
        break;
    }
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header style={{ background: '#fff' }}>
        <Menu mode="horizontal" defaultSelectedKeys={['1']}>
          <Menu.Item key="1" icon={<AppstoreOutlined />}>产品管理系统</Menu.Item>
        </Menu>
      </Header>
      <Content style={{ padding: '0 50px' }}>
        <Layout style={{ padding: '24px 0', background: '#fff' }}>
          <Content style={{ padding: '0 24px', minHeight: 280 }}>
            <Tabs defaultActiveKey="1">
              <TabPane tab="产品管理" key="1">
                <Row gutter={16} style={{ marginBottom: 16 }}>
                  <Col span={8}>
                    <Input.Search
                      placeholder="搜索产品"
                      onSearch={(value) => handleSearch('product', value)}
                      style={{ width: 200 }}
                    />
                  </Col>
                  <Col span={16} style={{ textAlign: 'right' }}>
                    <Button onClick={() => handleAdd('product')} type="primary" icon={<SearchOutlined />}>
                      添加产品
                    </Button>
                  </Col>
                </Row>
                <Table columns={productColumns} dataSource={filteredProducts} rowKey="id" />
              </TabPane>
              <TabPane tab="规格管理" key="2">
                <Row gutter={16} style={{ marginBottom: 16 }}>
                  <Col span={8}>
                    <Input.Search
                      placeholder="搜索规格"
                      onSearch={(value) => handleSearch('specification', value)}
                      style={{ width: 200 }}
                    />
                  </Col>
                  <Col span={16} style={{ textAlign: 'right' }}>
                    <Button onClick={() => handleAdd('specification')} type="primary" icon={<SearchOutlined />}>
                      添加规格
                    </Button>
                  </Col>
                </Row>
                <Table columns={specificationColumns} dataSource={filteredSpecifications} rowKey="id" />
              </TabPane>
              <TabPane tab="功能点管理" key="3">
                <Row gutter={16} style={{ marginBottom: 16 }}>
                  <Col span={8}>
                    <Input.Search
                      placeholder="搜索功能点"
                      onSearch={(value) => handleSearch('feature', value)}
                      style={{ width: 200 }}
                    />
                  </Col>
                  <Col span={16} style={{ textAlign: 'right' }}>
                    <Button onClick={() => handleAdd('feature')} type="primary" icon={<SearchOutlined />}>
                      添加功能点
                    </Button>
                  </Col>
                </Row>
                <Table columns={featureColumns} dataSource={filteredFeatures} rowKey="id" />
              </TabPane>
            </Tabs>
          </Content>
        </Layout>
      </Content>
      <Modal
        title={`${modalType === 'product' ? '产品' : modalType === 'specification' ? '规格' : '功能点'}信息`}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={() => setIsModalVisible(false)}
        confirmLoading={loading}
      >
        <Form form={form} layout="vertical">
          {modalType === 'product' && (
            <>
              <Form.Item name="name" label="产品名称" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
              <Form.Item name="description" label="描述">
                <Input.TextArea />
              </Form.Item>
            </>
          )}
          {modalType === 'specification' && (
            <>
              <Form.Item name="productId" label="产品ID" rules={[{ required: true }]}>
                <Select>
                  {products.map(product => (
                    <Select.Option key={product.id} value={product.id}>{product.name}</Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="name" label="规格名称" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
              <Form.Item name="price" label="价格" rules={[{ required: true }]}>
                <Input type="number" />
              </Form.Item>
              <Form.Item name="period" label="周期" rules={[{ required: true }]}>
                <Select>
                  <Select.Option value="月">月</Select.Option>
                  <Select.Option value="季">季</Select.Option>
                  <Select.Option value="年">年</Select.Option>
                </Select>
              </Form.Item>
            </>
          )}
          {modalType === 'feature' && (
            <>
              <Form.Item name="productId" label="产品ID" rules={[{ required: true }]}>
                <Select>
                  {products.map(product => (
                    <Select.Option key={product.id} value={product.id}>{product.name}</Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="specificationId" label="规格ID" rules={[{ required: true }]}>
                <Select>
                  {specifications.map(spec => (
                    <Select.Option key={spec.id} value={spec.id}>{spec.name}</Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="name" label="功能名称" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
              <Form.Item name="usageLimit" label="使用限制" rules={[{ required: true }]}>
                <Input type="number" />
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>
    </Layout>
  );
};

export default App;